<template>
  <div>
    <el-card>
      <div class="header">
        <el-row type="flex">
          <!-- 添加经纪按钮 -->
          <el-col>
            <el-button type="primary" size="small" @click="addAgents">
              添加经纪
            </el-button>
          </el-col>
          <el-col type>
            <el-row type="flex" justify="end">
              <!-- 搜索输入框 -->
              <el-input v-model.trim="searchVal" placeholder="请输入内容(值为空时为重置)" class="input-with-select" style="width:800px" @input="searchInput">
                <el-button slot="append" icon="el-icon-search" @click="searchAgents" />
              </el-input>
            </el-row>
          </el-col>
        </el-row>
      </div>
      <!-- 经纪表格 -->
      <div class="content">
        <el-table border="" :data="agentsList">
          <el-table-column label="图片" prop="image">
            <template #default="{ row }">
              <img :src="row.image" alt="" class="agentsImg">
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="name" />
          <el-table-column label="邮箱" prop="email" />
          <el-table-column label="电话" prop="phone" />
          <el-table-column label="地址" prop="address" />
          <el-table-column label="介绍" prop="desc" />
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                @click="updateAgents(row.id)"
              >编辑</el-button>
              <el-button
                type="danger"
                size="small"
                @click="delAgents(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页组件 -->
      <div class="footer">
        <el-row type="flex" justify="center">
          <el-pagination
            :total="pageTotal"
            layout="prev, pager, next"
            :page-size="pageSetting._limit"
            :current-page="currentPage"
            @current-change="currentChange"
          />
        </el-row>

      </div>
    </el-card>
    <!-- 新增和编辑的弹窗 -->
    <el-dialog :title="`${formData.id?'编辑':'新增'}经纪`" :visible="isShowDialog" @close="btnCancel">
      <!-- 表单 -->
      <el-form
        ref="addAgents"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="formData.name"
            style="width: 90%"
            placeholder="请输入姓名"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="formData.email"
            style="width: 90%"
            placeholder="请输入邮箱"
          />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input
            v-model="formData.phone"
            style="width: 90%"
            placeholder="请输入电话"
          />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input
            v-model="formData.address"
            style="width: 90%"
            placeholder="请输入地址"
          />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input
            v-model="formData.desc"
            style="width: 90%"
            placeholder="请输入描述"
          />
        </el-form-item>
        <el-form-item label="图片">
          <template>
            <UploadImage ref="upImg" @removeUrl="removeUrlFn" @imgUrl="imgUrlFn" />
          </template>
        </el-form-item>
      </el-form>
      <!-- footer插槽 -->
      <template #footer>
        <el-button size="small" @click="btnCancel">取消</el-button>
        <el-button
          type="primary"
          size="small"
          @click="btnOK"
        >确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getAgentsList, addAgentsList, getAgentsById, delAgents, editAgents, searchAgents, countAgents } from '@/api/agents'
import UploadImage from './components/UploadImage.vue'

export default {
  components: { UploadImage },
  data() {
    return {
      isSearch: false,
      currentPage: 0,
      pageSetting: {
        _start: 0,
        _limit: 2
      },
      pageTotal: 0,
      searchVal: '',
      isShowDialog: false,
      agentsList: [],
      formData: {
        name: '',
        email: '',
        phone: '',
        address: '',
        desc: '',
        image: ''
      },
      rules: {
        name: [{
          required: true, message: '不能为空', trigger: 'blur'
        }],
        email: [{
          required: true, message: '不能为空', trigger: 'blur'
        }, {
          pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '必须是邮箱规则', trigger: 'blur'
        }],
        phone: [{
          required: true, message: '不能为空', trigger: 'blur'
        }],
        address: [{
          required: true, message: '不能为空', trigger: 'blur'
        }],
        desc: [{
          required: true, message: '不能为空', trigger: 'blur'
        }],
        image: [{
          required: true, message: '不能为空', trigger: 'blur'
        }]
      }
    }
  },
  created() {
    this.getAgentsList()
  },
  methods: {
    // 搜索框的监听
    async searchInput() {
      if (!this.searchVal) {
        this.searchVal = ''
        const { data } = await getAgentsList({ _start: 0,
          _limit: 2 })
        this.agentsList = data
        const res = await countAgents()
        this.pageTotal = res.data
        this.currentPage = 1
      }
    },
    removeUrlFn(url) {
      if (url.length === 0) {
        url = 'http'
      }
      this.formData.image = url
    },
    async currentChange(newPage) {
      // 如果不为空 则视为在搜索 显示和分页都是显示搜索的结果列表
      if (this.searchVal !== '' && this.isSearch) {
        this.currentPage = newPage
        this.pageSetting._start = (newPage - 1) * this.pageSetting._limit
        const res = await searchAgents({ name_contains: this.searchVal, ...this.pageSetting })
        this.agentsList = res.data
        return
      }
      this.currentPage = newPage
      this.pageSetting._start = (newPage - 1) * this.pageSetting._limit
      this.getAgentsList()
    },
    async searchAgents() {
      this.isSearch = true
      let res = []
      if (this.searchVal === '') {
        const res = await getAgentsList({ _start: 0,
          _limit: 2 })
        this.agentsList = res.data
        const str = await countAgents()
        this.pageTotal = str.data
        this.currentPage = 1
        this.isSearch = false
        return
      }
      res = await searchAgents({ name_contains: this.searchVal, _start: 0,
        _limit: 2 })
      this.agentsList = res.data
      const str = await searchAgents({ name_contains: this.searchVal })
      this.pageTotal = str.data.length
      this.currentPage = 1
      // this.getAgentsList()
    },
    imgUrlFn(url) {
      this.formData.image = url
    },
    async getAgentsList() {
      const res = await getAgentsList(this.pageSetting)
      const str = await countAgents()
      this.pageTotal = str.data
      this.agentsList = res.data
    },
    addAgents() {
      this.isShowDialog = true
    },
    async delAgents(id) {
      await this.$confirm('确定要删除嘛?')

      await delAgents(id)
      if (this.pageTotal - this.pageSetting._start === 1) {
        this.pageSetting._start = this.pageSetting._start - this.pageSetting._limit
      }
      this.$message.success('操作成功')

      this.getAgentsList()
    },
    async updateAgents(id) {
      const res = await getAgentsById(id)
      this.formData = res.data
      this.$nextTick(() => {
        this.$refs.upImg.fileList = [
          { url: res.data.image }
        ]
      })

      this.isShowDialog = true
    },
    async btnOK() {
      // 校验表单
      await this.$refs.addAgents.validate()
      if (this.formData.id) {
        await editAgents(this.formData)
      } else {
        await addAgentsList(this.formData)
      }
      // 提示用户
      this.$message.success('操作成功')
      // 刷新数据
      this.getAgentsList()
      // 关闭弹窗
      this.isShowDialog = false
    },
    btnCancel() {
      this.formData = {
        name: '',
        email: '',
        phone: '',
        address: '',
        desc: '',
        image: ''
      }
      this.$refs.upImg.fileList = []
      // 每次点击取消,重置数据
      this.$refs.addAgents.resetFields()
      this.isShowDialog = false
    }

  }
}
</script>

<style lang="scss" scoped>
.header{
  padding-bottom: 10px;
  border-bottom: 1px solid #f5f5f5;
  margin-bottom: 20px;
}
.el-card{
  margin: 10px;
}
.agentsImg{
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover
}
.footer{
  border-top: 1px solid #f5f5f5;
  margin-top: 20px;
}
</style>
